import { Inject, Injectable } from '@nestjs/common';
import { CreateChannelDto } from './dto/create-channel.dto';
import { UpdateChannelDto } from './dto/update-channel.dto';
import { Channel } from './entities/channel.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RedisService } from 'src/redis/redis.service';


@Injectable()
export class ChannelService {
    @InjectRepository(Channel)
    private channelRepository: Repository<Channel>;

    引入redis
    @Inject(RedisService)
    private redisService: RedisService;

    async init() {
        const c1 = this.channelRepository.create({
            title: "基于 Axios 封装一个完美的双 token 无感刷新",
            content: "用户登录之后，会返回一个用户的标识，之后带上这个标识请求别的接口，就能识别出该用户。"
        })
        const c2 = this.channelRepository.create({
            title: "title2",
            content: "content2"
        })
        await Promise.all([
            this.channelRepository.save(c1),
            this.channelRepository.save(c2)
        ]);
        return 'done'
    }
    findAll() {
        return 'channel findall'
    }

    fineOneById(id: number) {
        return this.channelRepository.findOne({ where: { id } })
    }

    async viewCountAdd(id: number) {
        const channel = await this.fineOneById(id)
        channel.viewCount++
        await this.channelRepository.save(channel)
        return channel
    }


    async viewByRedis(id: number) {
        const res = await this.redisService.hashGet(`channel_${id}`)
        const channel = await this.fineOneById(id)
        if (res.viewCount === undefined) {
            // 存入数据库
            channel.viewCount++
            await this.channelRepository.update({ id }, {
                viewCount: channel.viewCount
            })
            // 存入redis
            await this.redisService.hashSet(`channel_${id}`, { viewCount: channel.viewCount })
            return channel
        } else {
            await this.redisService.hashSet(`channel_${id}`, {
                ...res,
                viewCount: +res.viewCount + 1
            })
            channel.viewCount = +res.viewCount + 1 // 暂时用redis 的阅读量代替 原来的旧值
            return channel
        }
    }

    async redisSyncData(){
        const keys = await this.redisService.keys(`channel_*`)
        console.log(keys ,"keys"); // 先获取所有的key
        keys.forEach( async (key) => {
            const res = await this.redisService.hashGet(key)
            const [ , id] = key.split('_') // 解构出id
            // 更新到数据库
            await this.channelRepository.update({id:+id} , {
                viewCount:+res.viewCount
            })
        })
    }
}
